var vo=new Vue({
    el:"#tab",
    data:{
        areaList:{areaList:[],carList:[]},
        time:{startTime:"",endTime:""},
        device:{location:[],marker:null},
        jsession: null,
        isInitFinished: false,
        swfwidth: 0,//swf插件窗口宽度
        swfheight: 0,//swf 插件窗口高度
        chnCount: 4,//默认通道数
        serverIp: "",//请求的服务器ip
        serverPort: "",//请求的服务器端口
        isLoadLoginServer: false,
        fileList: []
    },
    methods:{
        selectProjectList:function (data) {
            $.ajax({
                type: "GET",
                url:  baseURL + 'xinpai/project/list',
                contentType: "application/json",
                data: data,
                success: function(r){
                    if(r.code === 0){
                        vo.areaList.areaList=r.list;
                        vo.$nextTick(function () {
                            $('.collapse').collapse('hide');
                        })
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        selectCarList:function (data) {
            $.ajax({
                type: "GET",
                url:  baseURL + 'xinpai/car/select',
                contentType: "application/json",
                data: data,
                success: function(r){
                    if(r.code === 0){
                        vo.areaList.carList=r.list;
                        r.list.forEach(function (obj) {
                            $("#carId").append(`<option value="${obj.videoId}">${obj.plateNum}</option>`)
                        })
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        show(vid,id){
            playLiveVideo(id,vid);
        }
    },
    created(){
        this.selectProjectList({parentId:GetRequest().pid,type:1});
        this.selectCarList({nexus:'true',project_id:GetRequest().pid});
        initPlayerExample()
        //十分秒年月日范围，限制开始结束相隔天数小于30天

    }
})
/**
 * 用户登录
 * @param username
 * @param password
 */
var login = function (username, password) {
    if (username != null && password != null) {

        $.ajax(
            {
                type: 'get',
                url: `http://120.25.214.26/StandardApiAction_login.action?account=${username}&password=${password}`,
                dataType: 'jsonp',
                success: function (data) {
                    let {jsession, result} = data;
                    if (result == 0) {
                        vo.jsession = jsession;
                        lang.jsession = jsession;
                        lang.devIdno = "50960"
                        //getLng();
                    } else {
                        alert(`登录失败错误代码:${result}`);
                    }
                },
                error: function () {
                    alert('登录失败');
                }
            }
        );
    }
}
/**
 * 用户注销
 * @param jsession
 */
var logout = function (jsession) {

    if (jsession) {
        $.ajax(
            {
                type: 'get',
                url: `http://120.25.214.26/StandardApiAction_logout.action?jsession=${jsession}`,
                dataType: 'jsonp',
                success: function (data) {
                    console.log(data);
                    reSetVideo()
                }
            }
        );
    }
}

//播放视频
function playVideo1() {
    let html = `http://120.25.214.26/808gps/open/player/RealPlayVideo.html?account=xinpai&password=000000&PlateNum=50960&lang=zh`;
    $("#divPlugin").attr("src", html);
}

//停止播放视频
function stopVideo1() {
    $("#divPlugin").attr("src", "");
}

//获取gps信息
function getLng() {
    $.ajax(
        {
            type: 'get',
            url: `http://120.25.214.26/StandardApiAction_getDeviceStatus.action?jsession=${vo.jsession}&devIdno=50960&toMap=2`,
            dataType: 'jsonp',
            success: function (data) {
                var gps = [parseFloat(data.status[0].mlng), parseFloat(data.status[0].mlat)]
                console.log(gps);
                AMap.convertFrom(gps, 'baidu', function (status, info) {
                    console.log(info);
                    if (info.info === 'ok') {
                        var lnglats = info.locations[0]; // Array.<LngLat>
                        onComplete(lnglats)
                    }
                });
            }
        }
    );
}

//解析定位结果
function onComplete(data) {
    console.log(data.position);
    //map.setCenter(data.position);
    marker = new AMap.Marker({
        icon: "../img/car.png",
        map: map,
        position: data
    });
    marker.on("click", function () {
        $('#myModal').modal('show');
        initPlayerExample()
    })
    var str = ['定位成功'];
    str.push('经度：' + data.getLng());
    str.push('纬度：' + data.getLat());
    str.push('是否经过偏移：' + (data.isConverted ? '是' : '否'));
    document.getElementById('tip').innerHTML = str.join('<br>');
    map.setFitView();
}

//解析定位错误信息
function onError(data) {
    document.getElementById('tip').innerHTML = '定位失败';
}

//关闭窗口
function deleteWindow() {
    stopLiveVideo()
    $("#text").empty();
    $("#text").append("<div id='cmsv6flash'></div>")
    $("#table").bootstrapTable('destroy');
}
$('#time').datepicker({
    "autoclose": true, "format": "yyyy-mm-dd", "language": "zh-CN"
});

$("#sou").click(function () {
    $("#sou").attr("disabled",true);
    $("#sou").text("搜索中....")
    let date = $("#time").val();
    let videoId=$("#carId").val();
    console.log(videoId,date);
    if (date.indexOf("-") != -1&&videoId!=0&&videoId!=null) {
        //http://120.25.214.26:6604/3/5/callback=getData?DownType=2&jsession=${vo.jsession}&DevIDNO=50960&LOC=2&CHN=-1&YEAR=${da[0]}&MON=${parseInt(da[1])}&DAY=${da[2]}&RECTYPE=-1&FILEATTR=2&BEG=0&END=86399&ARM1=0&ARM2=0&RES=0&STREAM=0&STORE=0
        let da = date.split("-");
        if (vo.isLoadLoginServer) {
            $("#table").bootstrapTable('destroy');
            vo.isLoadLoginServer = false;
        }

        $.ajax({
            type:'get',
            url:`http://120.25.214.26:6604/3/5/callback=getData?DownType=2&jsession=${vo.jsession}&DevIDNO=${videoId}&LOC=2&CHN=-1&YEAR=${da[0]}&MON=${parseInt(da[1])}&DAY=${da[2]}&RECTYPE=-1&FILEATTR=2&BEG=0&END=86399&ARM1=0&ARM2=0&RES=0&STREAM=0&STORE=0`,
            dataType: 'jsonp',
            success:getData =function (json) {
                    console.log(json);

                    if (json.result == 0&&json.files!=null&& json.files.length > 0) {
                        vo.fileList=[];
                        for (var i = 0; i < json.files.length; i++) {
                            var obj = json.files[i];
                            let startTime = TimeNum(obj.beg);
                            let endTime = TimeNum(obj.end);
                            vo.fileList.push({
                                name: obj.file,
                                len: parseInt(obj.len / 1024 / 1024)+ "M",
                                type: obj.type,
                                recing: obj.recing,
                                time: startTime + "-" + endTime,
                                chn: "CH1,CH2,CH3,CH4"
                            })
                        }
                        tableInit(vo.fileList);
                    }
                $("#sou").text("录像查询")
                $("#sou").attr("disabled",false);
                },
                error:function(e){
                    console.log(e);
                }
            });
    } else {
        alert("请输入正确的时间")
    }
})

function TimeNum(s) {
    let hour = parseInt(s / 3600);
    let m = parseInt((s - hour * 3600) / 60);
    return hour + ":" + m;
}

function tableInit(data) {
    $('#table').bootstrapTable({
        data: data,
        striped: true,
        pagination: true,
        pageSize: 5,
        search:true,
        sortName: 'time',
        columns: [
            {
                field:"time",
                title:"时间"
            },
            {
            field: 'chn',
            title: '通道'
        }, {
            field: 'type',
            title: '类型',
            formatter: function (value) {
                if (value == 0) {
                    return "常规录像"
                } else {
                    return "报警录像"
                }
            }
        }, {
            field: 'len',
            title: '文件大小'
        },
            {
                field: 'name',
                title: "文件名"
            },{
            field:'name',
            title:"操作",
                formatter:function (value) {
                    let v=value;
                    return `<button type="button" class="btn btn-primary btn-sm" value="${v}"  onclick="test(this)">播放</button>`;
                }
            }

        ],
    });
}
//视频插件要初始化完成后才能调用
//开始远程回放
function test(obj) {
    let name=$(obj).val()

    //停止远程回放
    swfobject.getObjectById("cmsv6flash").stopVideo(0);
    //开始远程回放
    let html=`http://120.25.214.26:6604/3/5?DownType=5&DevIDNO=50960&FILELOC=1&FILESVR=0&FILECHN=0&FILEBEG=1&FILEEND=100&PLAYIFRM=0&PLAYFILE=${name}&PLAYBEG=0&PLAYEND=0&PLAYCHN=0`
    console.log(html);
    var ret = swfobject.getObjectById("cmsv6flash").startVod(0,html );
}
//停止远程回放
function stopPlayback() {
    swfobject.getObjectById("cmsv6flash").stopVideo(0);
}
